package com.jmx.yp.service.group;

import java.util.*;
import org.dom4j.*;
import com.jmx.yp.common.SysConstants;
import com.jmx.yp.dao.IBaseDao;
import com.jmx.yp.entity.GroupInfo;
import com.jmx.yp.entity.Menus;
import com.jmx.yp.exception.*;

/**
 * 
 * 功能描述：
 *			实现组织机构的业务逻辑
 * @author Jenny
 *
 * Date:2011-1-27 上午12:15:17
 */
public class GroupinfoService implements IGroupinfoService{

	private IBaseDao dao;

	
	private final String ROOT_IM0 = "folderClosed.gif";
	
	private final String ROOT_IM1 ="folderOpen.gif";
	
	private final String ROOT_IM2 = "folderClosed.gif";
		
	private final String CHILD_IM0 = "book_titel.gif";
	
	private final String CHILD_IM1 = "book.gif";
	
	private final String CHILD_IM2 = "book_titel.gif";
	
	public void setDao(IBaseDao dao){
		this.dao = dao;
	}
	
	/**
	 * 根据组织编号找出下级组织信息
	 * @param groupId
	 * @param loadCurrentGroupFlag 是否需要加载当前组织的标志
	 * @throws Exception
	 */
	public List currentGroupChildes(Long _groupId, boolean loadCurrentGroupFlag) throws Exception{
		List list = dao.getList("com.jmx.yp.entity.GroupInfoMapper.getGroupChildesById", _groupId);
		
		List tList = new ArrayList();
		
		if(loadCurrentGroupFlag){
			GroupInfo rootGroup = (GroupInfo)dao.getObject("com.jmx.yp.entity.GroupInfoMapper.getGroupChildesById.getGroupinfoById", _groupId);
			tList.add(getGroupJSONObject(rootGroup, true));
		}
		
		if(list != null){
			for(Iterator its = list.iterator(); its.hasNext();){
				Map map = (Map)its.next();
				tList.add(getGroupJSONObject(map, false));
			}
		}
		
		return tList;
	}
	

	/**
	 * 组织满足界面显示的JSON格式的数据结构
	 * @param obj
	 * @param flag isLeaf:false
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private Map getGroupJSONObject(Object obj, boolean flag){
		Map rMap = new HashMap();
		if(flag){
			GroupInfo group = (GroupInfo)obj;
			
			rMap.put("id", group.getSERIALID());
			
			//groupObj.setPid(group.getUPGROUP());
			
			Map map = new HashMap();
			map.put("GROUP_LVL", group.getGROUP_LVL());
			map.put("GROUP_DIR", group.getGROUP_DIR());
			map.put("GROUP_CODE", group.getGROUP_CODE());
			map.put("GROUP_NAME", group.getGROUP_NAME());
			if(group.getGROUP_ADDR() != null || group.getGROUP_ADDR().length() > 0)
				map.put("GROUP_ADDR", group.getGROUP_ADDR());
			if(group.getGROUP_TEL() != null || group.getGROUP_TEL_AREA() != null || group.getGROUP_TEL_CN() != null)
				map.put("GROUPTEL",
						group.getGROUP_TEL_CN() == null ? "" : group.getGROUP_TEL_CN() + "-" +
						group.getGROUP_TEL_AREA() == null ? "" : group.getGROUP_TEL_AREA() + "-" +
						group.getGROUP_TEL() == null ? "" : group.getGROUP_TEL());
			if(group.getGROUP_FAX() != null || group.getGROUP_FAX_AREA() != null || group.getGROUP_FAX_CN() != null)
				map.put("GROUPFAX",
						group.getGROUP_FAX_CN() == null ? "" : group.getGROUP_FAX_CN() + "-" +
						group.getGROUP_FAX_AREA() == null ? "" : group.getGROUP_FAX_AREA() + "-" +
						group.getGROUP_FAX() == null ? "" : group.getGROUP_FAX());
			rMap.put("dataObject", map);
			//groupObj.setDataObject(map);
			
			Map userMap = new HashMap();
			userMap.put("isGroup", true);
			//groupObj.setUserObject(userMap);
			rMap.put("userObject", userMap);
		
		}else{
			Map map = (Map)obj;
			rMap.put("id", (Long)map.get("SERIALID"));
			rMap.put("pid",(Long)map.get("UPGROUP"));
			
			if((Integer)map.get("GROUP_NEXT") == GroupInfo.GROUP_HAS_CHILD){
				rMap.put("isLeaf", false);
				Map userObjectMap = new HashMap();
				userObjectMap.put("isGroup", true);
				//userObjectMap.put("groupName", map.get("GROUP_NAME").toString());
				rMap.put("userObject", userObjectMap);
			}
			
			map.remove("SERIALID");
			map.remove("UPGROUP");
			rMap.put("dataObject",map);
			
		}
		 
		return rMap;
	}
	
	/*
	 * 新增组织
	 */
	public void addGroup(GroupInfo info)throws Exception{
		 dao.saveObject("com.jmx.yp.entity.GroupInfoMapper.addGroup", info);
	}
	
	/*
	 * 新增组织后，修改父组织状态为有子孙
	 */
	public void updateGroupNext(Long groupId)throws Exception{
		 dao.updateObject("com.jmx.yp.entity.GroupInfoMapper.updateGroupNext", groupId);
	}
	
	/**
	 * 组织编号是否存在
	 * @return 有返回true，否则false
	 * @throws Exception
	 */	
	public boolean groupCodeIsDup(String groupcode) throws Exception{
		Integer count = (Integer)dao.getObject("com.jmx.yp.entity.GroupInfoMapper.groupCodeIsDup", groupcode);
		if(count > 0)
			return true;
		else
			return false;
	}

	/**
	 * 组织名称是否存在
	 * @return 有返回true，否则false
	 * @throws Exception
	 */	
	public boolean groupNameIsDup(String groupname) throws Exception{
		Integer count = (Integer)dao.getObject("com.jmx.yp.entity.GroupInfoMapper.groupNameIsDup", groupname);
		if(count > 0)
			return true;
		else
			return false;
	}
	
	/*
	 * 浏览组织
	 */
	public GroupInfo viewGroupInfo(Long groupId)throws Exception{
		GroupInfo ginfo= (GroupInfo)dao.getObject("com.jmx.yp.entity.GroupEmployeeMapper.getGroupinfoById", groupId);
		return ginfo;
	}
	
	/*
	 * 浏览组织后，修改组织
	 */
	public void updateGroupInfo(GroupInfo ginfo)throws Exception{
		dao.getObject("com.jmx.yp.entity.GroupEmployeeMapper.updateGroupInfo", ginfo);
	}
	
	/**
	 * 根据组织编号判断是否属于JMX
	 * @param groupId
	 * @return 属于JMX返回true，否则false
	 * @throws Exception
	 */
	public boolean isBlongToJMX(Long groupId) throws Exception{
		Integer count = (Integer)dao.getObject("com.jmx.yp.entity.GroupInfoMapper.isJmxGroup", groupId);
		if(count > 0)
			return true;
		else
			return false;
	}
	  
	/**
	 * 根据机构ID查询机构名称
	 * @param groupId 若为NULL时，表示查询杰马逊组织名称
	 * @return
	 * @throws Exception
	 */
	public Map getGroupNameById(Long groupId) throws Exception{		
		Map map = (Map)dao.getObject("com.jmx.yp.entity.GroupInfoMapper.getGroupNameById", groupId);
		return map;
	}

	
	/**
	 * 根据机构ID查询当前机构级别及父路径
	 * @param groupId 若为NULL时，表示查询杰马逊组织名称
	 * @return
	 * @throws Exception
	 */
    public Map getGroupLvlDirById(Long groupId) throws Exception{
    	Map<String, Long> paramMap = new HashMap<String, Long>(1);
    	paramMap.put("groupId", groupId);;
		Map map = (Map)dao.getObject("com.jmx.yp.entity.GroupInfoMapper.getGroupLvlDirById", paramMap);
		return map;
    }
    
	/**
	 * 根据组织有无根节点。针对超级管理员 操作
	 * @return 有返回true，否则false
	 * @throws Exception
	 */	
	public boolean hisGroupRoot() throws Exception{
		Integer count = (Integer)dao.getObject("com.jmx.yp.entity.GroupInfoMapper.hisRootGroup", null);
		if(count > 0)
			return true;
		else
			return false;
	}
	
	/**
	 * 组织机构及其向上父类是否被冻结
	 * @param groupId
	 * @return 冻结，返回true
	 * @throws Exception
	 */
	public boolean isFreezed(Long groupId) throws Exception{		
		GroupInfo group = (GroupInfo)dao.getObject(
						"com.jmx.yp.entity.GroupInfoMapper.getGroupinfoById", groupId);
		
		//如果是杰马逊员工，直接就返回true，不用判断组织机构名称
		if(group.getUPGROUP() == 0 && group.getGROUP_LVL() == 0)
			return false;
		
		if(group.getSTATE() == SysConstants.STATE_FROZEN)
			return true;
	
		if(group.getGROUP_DIR().equals("0"))
			return false;
		else{
			String tempDir = group.getGROUP_DIR().substring(1, group.getGROUP_DIR().length() -1);
			Integer count = (Integer)dao.getObject("com.jmx.yp.entity.GroupInfoMapper.countParentGroupFreezedState", 
						tempDir.split(";"));
			if(count == 0) 
				return false;
			else
				return true;
			
		}
	}
	
	/**
	 * 获取组织机构的根结点
	 * @param rootGroupId
	 * @param rootGroupName
	 * @param queryGroupName
	 * @param queryGroupCode
	 * @param flag 若为true，表示查询杰马逊机构管理员，只查询杰马逊及其下级组织即可。
	 * @return ID;NAME;CODE
	 * @throws Exception
	 */
	public String getGroupRoot(Long rootGroupId, String rootGroupName, String rootGroupCode, String queryGroupName, String queryGroupCode, boolean flag) throws Exception{
		Map map = new HashMap(); //设置查询条件
		
		if(queryGroupName != null && queryGroupName.trim().length() > 0){
			map.put("groupName", queryGroupName.trim());
		}
		if(queryGroupCode != null && queryGroupCode.trim().length() > 0){
			map.put("queryCode", queryGroupCode.trim());
		}			
		
		if(map.isEmpty())
			return rootGroupId + ";" + rootGroupName + ";" + rootGroupCode;
		
		if(flag){
			map.put("groupId", rootGroupId);
		}else{
			map.put("groupDir", "%;" + rootGroupId + ";%");
		}
		
		GroupInfo group = (GroupInfo)dao.getObject("com.jmx.yp.entity.GroupInfoMapper.getJMXChild", map);
		if(group == null) 
			throw new HandlerException(ErrorCode.ERR_2000);
				
		return group.getSERIALID() + ";" + group.getGROUP_NAME() + ";" + group.getGROUP_CODE();
	}
	
	/**
	 * 获取组织机构树形结构
	 * 	  备注：当组织机构与组织编码不为空时，表示查询在根树ID范围内的查询,对根结点为查询组织机构
	 * @param rootGroupId   根树ID
	 * @param queryGroupName 查询组织机构（可为空）
	 * @param queryGroupCode 查询组织机构编码（可为空）
	 * @param 若不为空，则表示查询杰马逊组织，否则为组织机构树查询
	 * @return 返回XML文件字符串
	 * @throws Exception 当前根树形ID下未查找到指定查询的组织机构或组织编码时，抛出业务操作异常
	 */
	public String getGroupTreeXML(Long rootGroupId, String rootGroupName, String groupCode, Long jmxId) throws Exception{
		//查询杰马逊机构及以下机构
		Document xmlDoc = null;
		Map map = new HashMap();
		List gList = null;
		
		if(jmxId != null){
			map.put("groupId", jmxId);
			if(rootGroupId.longValue() == jmxId)
				gList = dao.getList("com.jmx.yp.entity.GroupInfoMapper.getJMXChild", map);			
			
			xmlDoc = buildJMXTree(rootGroupId, rootGroupName, groupCode, gList);
		}else{			
			map.put("groupDir", "%;" + rootGroupId + ";%");
			gList = dao.getList("com.jmx.yp.entity.GroupInfoMapper.getJMXChild", map);
			xmlDoc = buildGroupTree(rootGroupId, rootGroupName, groupCode, gList);
		}
		
		return xmlDoc == null ? null : xmlDoc.asXML();
	}
	
	/**
	 * 构造组织结构树
	 *     采用递归算法
	 * @param root
	 * @param rootName
	 * @param list
	 * @return
	 * @throws Exception
	 */
	private Document buildGroupTree(Long root, String rootName, String rootCode, List list) throws Exception{
		 Document document = DocumentHelper.createDocument();   
	     document.setXMLEncoding("utf-8");   
	  
	     //加入XML树根点
	     Element tree = document.addElement("tree");   
	     tree.addAttribute("id", "0");
	     
	     //加入显示树根结点	
	     Element rootItem = tree.addElement("item");
	     rootItem.addAttribute("text", rootName);
	     rootItem.addAttribute("id", root.toString() + ";" + rootCode);
	     rootItem.addAttribute("open", "1");
	     rootItem.addAttribute("im0", ROOT_IM0);
	     rootItem.addAttribute("im1", ROOT_IM1);
	     rootItem.addAttribute("im2", ROOT_IM2);
	     
	     if(list != null || !list.isEmpty()){
	    	 for(Iterator its = list.iterator(); its.hasNext();){
	    		 GroupInfo group = (GroupInfo)its.next();
	    		 if(group.getUPGROUP().longValue() != root)
	    			 continue;
	    		 else{
	    			 
	    			 recursive(list, getSubElements(rootItem, group), group.getSERIALID());
	    		 }
	    	 }
	     }
	     
	     return document;
	}
	
	/**
	 * 递归生成树结点
	 * @param targetList
	 * @param sourceList
	 * @param id
	 */
	private void recursive(List sourceList, Element element, Long groupId){
		for(Iterator its = sourceList.iterator(); its.hasNext();){
			GroupInfo group = (GroupInfo)its.next();
			if(group.getUPGROUP().longValue() == groupId){				
				recursive(sourceList, getSubElements(element, group), group.getSERIALID());
			}
		}
	}
	
	/**
	 * 构造杰马逊及下级组织机构XML
	 * @param root
	 * @param rootName
	 * @param list
	 * @return
	 * @throws Excpetion
	 */
	private Document buildJMXTree(Long root, String rootName, String rootCode, List list) throws Exception{
		 Document document = DocumentHelper.createDocument();   
	     document.setXMLEncoding("utf-8");   
	  
	     //加入XML树根点
	     Element tree = document.addElement("tree");   
	     tree.addAttribute("id", "0");
	     
	     //加入显示树根结点	
	     Element rootItem = tree.addElement("item");
	     rootItem.addAttribute("text", rootName);
	     rootItem.addAttribute("id", root.toString() + ";" + rootCode);
	     rootItem.addAttribute("open", "1");
	     rootItem.addAttribute("im0", ROOT_IM0);
	     rootItem.addAttribute("im1", ROOT_IM1);
	     rootItem.addAttribute("im2", ROOT_IM2);
	     
	     if(list != null && !list.isEmpty()){
	    	 for(Iterator its = list.iterator(); its.hasNext();){
	    		 GroupInfo group = (GroupInfo)its.next();
	    		 getSubElements(rootItem, group);
	    	 }
	     }
	     
	    return document;   
	}
	
	/**
	 * 构造子元素
	 * @param element
	 * @param group
	 */
	private Element getSubElements(Element element, GroupInfo group){
		 Element subItem = element.addElement("item");
		 subItem.addAttribute("text", group.getGROUP_NAME());   
	     subItem.addAttribute("id", group.getSERIALID().toString() + ";" + group.getGROUP_CODE());   
	     subItem.addAttribute("im0", CHILD_IM0);   
	     subItem.addAttribute("im1", CHILD_IM1);   
	     subItem.addAttribute("im2", CHILD_IM2);
	     return subItem;
	}
	
	
	/**
	 * 根据组织代码或名称判断是否属于指定的组织及其子组织
	 * @param apponitGroupId
	 * @param groupCode
	 * @param groupName
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public boolean isBelongToAppointGroup(Long appointGroupId, String groupCode, String groupName) throws Exception{
		boolean flag = false;
		
		Map paramMap = new HashMap();
		paramMap.put("appointGroupId", appointGroupId);
		if(groupCode != null && groupCode.trim().length() > 0)
			paramMap.put("groupCode", groupCode);
		if(groupName != null && groupName.trim().length() > 0)
			paramMap.put("groupName", groupName);
		
		int count = (Integer)dao.getObject("com.jmx.yp.entity.GroupInfoMapper.isBelongToAppointGroup", paramMap);
		
		if(count > 0)
			flag = true;
		
		return flag;
	}
	
	public static void main(String[] args){
		String sss = ";1;2;3;5;";
		String temp = sss.substring(1, sss.length() -1);
		System.out.println(temp.replace(';', ','));
	}
}
